const axios = require('axios');
const { OpenAI } = require('openai');
const openai = new OpenAI({
  apiKey: process.env.DASHSCOPE_API_KEY,
  baseURL: "https://dashscope.aliyuncs.com/compatible-mode/v1"
});
// 流式调用OpenAI接口
async function* streamOpenAIResponse(messages, model = "deepseek-r1") {
  const url = "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions";
  const headers = {
    "Content-Type": "application/json",
    "Authorization": `Bearer ${process.env.DASHSCOPE_API_KEY}`
  };

  // 请求数据
  const data = {
    model,
    messages,
    temperature: 0.7,
    stream: true
  };

  try {
    // 发送请求
    const response = await axios.post(url, data, {
      headers,
      responseType: 'stream' // 获取流式响应
    });

    let buffer = '';     // 缓冲区
    let think = '';      // 思考内容
    let fullResponse = ''; // 完整响应

    // 处理流数据
    for await (const chunk of response.data) {
      const lines = chunk.toString().split('\n');

      for (const line of lines) {
        if (line.startsWith('data: ')) {
          const data = line.slice(6);
          if (data === '[DONE]') {
            // 流结束
            if (buffer) {
              yield { type: 'stream', content: buffer };
            }
            yield {
              type: 'final',
              think,
              content: fullResponse
            };
            return;
          }

          try {
            const json = JSON.parse(data);
            const delta = json.choices[0].delta;

            // 处理思考内容
            if (delta.reasoning_content) {
              think += delta.reasoning_content;
            }

            // 处理响应内容
            if (delta.content) {
              const content = delta.content;
              fullResponse += content;
              buffer += content;

              // 当缓冲区达到一定大小或遇到特定字符时发送
              if (buffer.length >= 10 || ['\n', '。', '，', '！', '？'].some(c => buffer.includes(c))) {
                yield { type: 'stream', content: buffer };
                buffer = '';
              }
            }
          } catch (e) {
            console.error('JSON解析错误:', e);
          }
        }
      }
    }
  } catch (e) {
    console.error('OpenAI请求错误:', e);
    throw e;

  }
}
// 直接输出答案
async function analyzeData(messages) {
  try {
    const completion = await openai.chat.completions.create({
      model: "deepseek-r1",
      messages
    });
    return {
      reasoning_content: completion.choices[0].message.reasoning_content,
      content: completion.choices[0].message.content
    };
  } catch (error) {
    console.error("发生错误:", error);
  }
}
module.exports = {
  analyzeData,
  streamOpenAIResponse
};